﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Timers;
using System.Web;
using System.IO;
using Dimebrain.TweetSharp.Fluent;
using Dimebrain.TweetSharp.Fluent.Services;


public class WebPhoto
{
	//const string UrlPath = "http://betty2/betty/images/";
	public static string[] GetPhotos(int count, string serverPath, string uriPath)
	{
		//NOTE: Change hardcoded strings later
		var dr = new DirectoryInfo(serverPath);
		var result = from f in dr.EnumerateFiles()
					 orderby f.CreationTime descending
					 select Path.Combine(uriPath, f.Name);

		//pull top X # 
		return result.Take(count).ToArray();
	}

	public static void UploadPicture(string userName, string password, string filePath, string message)
	{
		if (File.Exists(filePath))
		{
			FluentTwitter.CreateRequest()
				.AuthenticateAs(userName, password)
				.Photos()
				.PostPhoto(filePath)
				.Statuses().Update(message)
				.Request();
		}
	}

	private readonly Timer _timer;

	private int _photoCount;
	private Uri _cameraUrl;
	private string _savePath;

	public WebPhoto()
	{
		_timer = new Timer();
		_timer.Elapsed += PhotoTimer_Elapsed;
	}

	// if photocount == 0, won't stop, else will stop once count == 0
	public void StartSavingPhotos(Uri cameraUrl, string savePath, double interval, int photoCount = 0)
	{
		_cameraUrl = cameraUrl;
		_savePath = savePath;
		_timer.Interval = interval;
		_photoCount = photoCount;
		 if (!_timer.Enabled)        
			_timer.Start();
	}

	public void StopSavingPhotos()
	{
		if (_timer.Enabled)    
			_timer.Stop();
	}

	void PhotoTimer_Elapsed(object sender, ElapsedEventArgs e)
	{
		// by photo count
		if (_photoCount-- <= 0)
			StopSavingPhotos();

		var fileName = Path.Combine(_savePath, String.Format("{0}.jpg", DateTime.Now.ToString("yyyyMMddHHmmssff")));
		
		// to get this plus twitpic working, had to set proxy to null
		// this is hugely due to us having a proxy server internal.
		var wc = new WebClient {Proxy = null};
		wc.DownloadFileAsync(_cameraUrl, fileName );
	}
}